package org.example.new_hbps_backend_reconstruction.controller.patient;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.entity.PatientBaseEntity;
import org.example.new_hbps_backend_reconstruction.entity.PatientDeviceEntity;
import org.example.new_hbps_backend_reconstruction.entity.request.ImportPatientBaseListRequest;
import org.example.new_hbps_backend_reconstruction.service.PatientAvatarService;
import org.example.new_hbps_backend_reconstruction.service.PatientBaseService;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 丁利军
 * @date 2025年10月10日 20:42
 * @description 患者基本信息
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/patient/patientBase")
@Tag(name = "患者基本信息管理", description = "提供患者基本信息的查询、修改、新增、删除、导入导出等接口")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class PatientBaseController {

    private final PatientBaseService patientBaseService;
    // 添加头像服务依赖
    private final PatientAvatarService patientAvatarService;

    @Operation(summary = "查询年龄性别统计", description = "根据医生ID查询该医生管理的患者年龄与性别统计信息。")
    @Parameter(name = "doctorUid", description = "医生唯一标识ID", required = true)
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/{doctorUid}/patient/stats")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getPatientStatistics(@PathVariable("doctorUid") Long doctorUid) {
        return R.ok(patientBaseService.getPatientStatistics(doctorUid));
    }

    @Operation(summary = "查询特别关心患者的年龄性别统计", description = "根据医生ID查询特别关注患者的年龄与性别统计信息。")
    @Parameter(name = "doctorUid", description = "医生唯一标识ID", required = true)
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/{doctorUid}/patient/bycarestats")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getPatientbycareStatistics(@PathVariable("doctorUid") Long doctorUid) {
        return R.ok(patientBaseService.getPatientbycareStatistics(doctorUid));
    }

    @Operation(summary = "自定义分页查询", description = "分页查询患者基础信息（带特别关心字段筛选）。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "403", description = "权限不足")
    })
    @GetMapping("/page_custom")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getPatientBasePageByCare(@ParameterObject Page<?> page) {
        return R.ok(patientBaseService.pageByCare(page));
    }

    @Operation(summary = "分页查询患者基础信息", description = "标准分页查询接口，用于获取患者基本信息列表。")
    @Parameters({
            @Parameter(name = "page", description = "分页参数对象", required = true),
            @Parameter(name = "patientDevice", description = "患者设备筛选条件，可为空")
    })
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getPage(@ParameterObject Page page,
                     @ParameterObject PatientDeviceEntity patientDevice) {
        LambdaQueryWrapper<PatientBaseEntity> wrapper = Wrappers.lambdaQuery();
        return R.ok(patientBaseService.page(page, wrapper));
    }

    @Operation(summary = "全条件查询患者信息", description = "根据患者信息对象的各字段进行多条件查询。")
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            required = true,
            description = "患者基础信息对象（可包含多个字段用于筛选）",
            content = @Content(schema = @Schema(implementation = PatientBaseEntity.class))
    )
    @PostMapping("/getByPatientBaseObject")
    //@PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getByPatientBaseObject(@RequestBody PatientBaseEntity patientBase) {
        LambdaQueryWrapper<PatientBaseEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.setEntity(patientBase);
        return R.ok(patientBaseService.list(wrapper));
    }

    @Operation(summary = "修改患者体力状况", description = "修改患者的体力状况字段信息。")
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            required = true,
            description = "包含患者ID和体力状况字段的对象",
            content = @Content(schema = @Schema(implementation = PatientBaseEntity.class))
    )
    @PostMapping("/edit_physical_strength")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_edit')")
    public R editPhysicalStrength(@RequestBody PatientBaseEntity patientBase) {
        String result = patientBaseService.editPhysicalStrength(
                patientBase.getPatientUid(), patientBase.getPhysicalStrength());
        if ("success".equals(result)) {
            return R.ok();
        } else {
            return R.failed(result);
        }
    }

    @Operation(summary = "查询患者姓名性别年龄", description = "根据患者ID查询姓名、性别和年龄。")
    @Parameter(name = "patientUid", description = "患者唯一标识ID", required = true)
    @GetMapping("/get_name_sex_age")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getPatientNameSexAge(@RequestParam Long patientUid) {
        log.info("查询患者姓名性别年龄，patientUid={}", patientUid);
        return R.ok(patientBaseService.getPatientNameSexAge(patientUid));
    }

    @Operation(summary = "通过ID查询患者基本信息", description = "根据患者唯一ID获取患者基本信息详情。")
    @Parameter(name = "patientUid", description = "患者唯一标识ID", required = true)
    @GetMapping("/{patientUid}")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_view')")
    public R getById(@PathVariable("patientUid") Long patientUid) {
        return R.ok(patientBaseService.getById(patientUid));
    }

    @Operation(summary = "新增患者基本信息", description = "添加新的患者基础信息记录。")
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            required = true,
            description = "患者基础信息对象",
            content = @Content(schema = @Schema(implementation = PatientBaseEntity.class))
    )
    @PostMapping
    public R save(@RequestBody PatientBaseEntity patientBase) {
        return R.ok(patientBaseService.save(patientBase));
    }

    @Operation(summary = "修改患者基本信息", description = "修改现有的患者基础信息记录。如果不存在则新增。")
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            required = true,
            description = "患者基础信息对象（包含要修改的字段）",
            content = @Content(schema = @Schema(implementation = PatientBaseEntity.class))
    )
    @PostMapping("/update_patient_base")
    //@PreAuthorize("@pms.hasPermission('patient_patientBase_edit')")
    public R updateById(@RequestBody PatientBaseEntity patientBase) {
        log.info("更新患者基本信息, patientUid={}, patientName={}", 
                patientBase.getPatientUid(), patientBase.getPatientName());
        
        // 使用 saveOrUpdate 代替 updateById，如果不存在则新增
        boolean result = patientBaseService.saveOrUpdate(patientBase);
        log.info("更新结果: {}", result);
        
        return R.ok(result);
    }

    @Operation(summary = "通过ID删除患者基本信息", description = "批量删除指定ID的患者信息。")
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
            required = true,
            description = "患者ID数组，例如：[1,2,3]",
            content = @Content(array = @ArraySchema(schema = @Schema(type = "long")))
    )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('patient_patientBase_del')")
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(patientBaseService.removeBatchByIds(CollUtil.toList(ids)));
    }

    @Operation(summary = "导出患者基本信息Excel", description = "根据条件导出患者基本信息为Excel文件。")
    @Parameters({
            @Parameter(name = "patientBase", description = "筛选条件，可为空"),
            @Parameter(name = "ids", description = "导出指定ID的患者信息，可为空")
    })
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('patient_patientBase_export')")
    public List<PatientBaseEntity> export(PatientBaseEntity patientBase, Long[] ids) {
        return patientBaseService.list(Wrappers.lambdaQuery(patientBase)
                .in(ArrayUtil.isNotEmpty(ids), PatientBaseEntity::getPatientUid, ids));
    }
    /**
     * 通过Excel批量导入患者病历，仅支持xls、xlsx格式
     */
    //TODO 这个方法暂时也注释掉，因为@RequestExcel注解是pigcloud框架提供的，如果需要，再直接从源码往过引入
//    @Operation(summary = "通过Excel批量导入患者病例", description = "通过Excel批量导入患者病例")
//    @PostMapping("/import")
//    @PreAuthorize("@pms.hasPermission('patient_patientBase_export')")
//    public R importPatientCase(@RequestExcel List<ImportPatientBaseListRequest> excelList,
//                               BindingResult bindingResult) {
//        return patientBaseService.importPatientBaseList(excelList, bindingResult);
//    }

}
